import './timeTo.less';

const timeTo = {
  name: 'timeTo',
  data () {
    return {
      computeNumber: [1,4],
      computeTime: {
        hour: [],
        minute: [],
        second: []
      }
    }
  },
  props:{
    time:{
      type: Object,
      required: true,
      default(){
        return {}
      }
    }
  },
  watch: {
    time: {
      handler: function(n,o){
        let arr = Object.keys(this.time);
        arr.forEach((item,index) => {
          let str = this.time[item];
          if(this.time[item] < 10){
            str = '0' + this.time[item]
          };
          this.computeTime[item] = [];
          this.computeTime[item].push(...(str+'').split('').map(Number));
        });
        this.$nextTick(()=>{
          this.increaseNumber();
        });
      },
      deep: true,
      immediate: true
    }
  },
  methods:{
    getRandomNumber (min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min)
    },
    // 定时增长数字
    increaseNumber () {
      this.setNumberTransform('hour')
      this.setNumberTransform('minute')
      this.setNumberTransform('second')
    },
    // 设置每一位数字的偏移
    setNumberTransform (index) {
      let numberItems = this.$refs[`numberItem${index}`]
      let numberArr = this.computeTime[index].filter(item => !isNaN(item))
      if(numberItems && numberItems.length > 0){
        for (let index = 0; index < numberItems.length; index++) {
          let elem = numberItems[index]
          elem.style.transform = `translate(-50%, -${numberArr[index] * 10}%)`
        }
      }
    },
    renderItem(mark){
      const listItem = this.computeTime[mark].map((item,index) => {
        if(!isNaN(item)){
          return (<li class={'number-item'}><span><i ref={`numberItem${mark}`} refInFor={true} key={index}>0123456789</i></span></li>)
        }else{
          return (<li class={'comma-item'}><span>{item}</span></li>)
        };
      });
      return <ul key={mark}>{listItem}</ul>
    }
  },
  render() {
    const dateList = ['hour','','minute','','second'];
    const listBox = dateList.map(item => {
      return item?this.renderItem(item):(<div class={'colon'}>:</div>)
    })
    return <div class={'time-box'} id={'time-wrap'}>{listBox}</div>
  },
};

export default timeTo
